import { login, logout, getInfo,getMenus } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  menu_filter :[],
  roles: [],
  permissions :[]
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },

  SET_ROLES: (state, roles) => {
    state.roles = roles
  },

  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }

}

const actions = {
  getMenus({ }) {

    return getMenus().then(res => {
      return res.data
    }).catch(err => {
      return err;
    })
  },
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response

        commit('SET_TOKEN', data.token)
        setToken(data.token)

        resolve()
      }).catch(error => {

        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response

        if (!data) {
          reject('获取用户信息失败,请重新登陆.')
        }

        const { username, avar,roles,permissions } = data

        commit('SET_NAME', username)
        commit('SET_AVATAR', avar)
        commit('SET_ROLES', roles)

        commit('SET_PERMISSIONS', permissions)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

